package com.tz.actions;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.tz.dao.ProductDao;
import com.tz.entity.Category;
import com.tz.entity.Picture;
import com.tz.entity.Product;
import com.tz.util.AcUtil;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.util.List;
import java.util.Map;

/**
 */
@Namespace("/")
public class IndexAction extends ActionSupport {

    private List<Category> categories;
    private List<Product> products;
    @Autowired
    private ProductDao productDao;

/*    public IndexAction() {
        Map<String,Object> application = ActionContext.getContext().getApplication();
        ApplicationContext ac = (ApplicationContext) application.get("ac");
        productDao = ac.getBean(ProductDao.class);
    }*/

    @Action(value = "index",results = {
            @Result(location = "/index.jsp")
    })
    public String execute() throws Exception {
        //ProductDao productDao = AcUtil.getAc().getBean(ProductDao.class);
        //查找父Category
        categories = productDao.findCategoryByCategoryId(0);
        //将子类Categories 设置给粑粑
        for(Category category:categories){
            List<Category> cates = productDao.findCategoryByCategoryId(category.getId());
            category.setChildren(cates);
        }
        //查找所有产品
        products = productDao.findAllProducts();
        List<Picture> pictures = null;
        for (Product p : products) {
            pictures = productDao.findPictureByProductId(p.getId());
            p.setPictures(pictures);
        }

        return SUCCESS;
    }

    public List<Category> getCategories() {
        return categories;
    }

    public void setCategories(List<Category> categories) {
        this.categories = categories;
    }

    public List<Product> getProducts() {
        return products;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    }
}
